package postgres

import (
	"context"
	"gorm.io/gorm"
	"manager/errors"
	"manager/model"
	"manager/model/entity"
)

var DeviceUpgradeRecode = &deviceUpgradeRecode{}

type deviceUpgradeRecode struct{}

// Create 创建
func (a *deviceUpgradeRecode) Create(ctx context.Context, m *entity.DeviceUpgradeRecode) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find 查找详情
func (a *deviceUpgradeRecode) Find(ctx context.Context, in *model.DeviceUpgradeRecodeInfoRequest) (*entity.DeviceUpgradeRecode, error) {
	e := &entity.DeviceUpgradeRecode{}

	q := GetDB(ctx).Model(&entity.DeviceUpgradeRecode{})

	if in.Id > 0 {
		err := q.First(&e, in.Id).Error
		return e, err
	}

	count := 0

	if in.FirmwareId != nil {

		q = q.Where("firmware_id = ?", in.FirmwareId)

		count++
	}

	if in.FirmwaresName != nil {

		q = q.Where("firmwares_name like ?", in.FirmwaresName)

		count++
	}

	if in.Version != nil {

		q = q.Where("version like ?", in.Version)

		count++
	}

	if in.TacticsId != nil {

		q = q.Where("tactics_id = ?", in.TacticsId)

		count++
	}

	if in.SnCode != nil {

		q = q.Where("sn_code = ?", in.SnCode)

		count++
	}

	if in.Desc != nil {

		q = q.Where("desc like ?", in.Desc)

		count++
	}

	if in.Status != nil {

		q = q.Where("status = ?", in.Status)

		count++
	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

		count++
	}

	if count == 0 {
		return e, errors.New("condition illegal")
	}

	err := q.First(&e).Error
	return e, err
}

// Update 更新
func (a *deviceUpgradeRecode) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.DeviceUpgradeRecode{}).Where("id = ?", id).Updates(dict).Error
}

// Delete 删除
func (a *deviceUpgradeRecode) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.DeviceUpgradeRecode{}, id).Error
}

// List 列表查询
func (a *deviceUpgradeRecode) List(ctx context.Context, in *model.DeviceUpgradeRecodeListRequest) (int, []*entity.DeviceUpgradeRecode, error) {
	var (
		q                    = GetDB(ctx).Model(&entity.DeviceUpgradeRecode{})
		err                  error
		total                int64
		deviceUpgradeRecodes []*entity.DeviceUpgradeRecode
	)

	if in.FirmwareId != nil {

		q = q.Where("firmware_id = ?", in.FirmwareId)

	}

	if in.FirmwaresName != nil {

		q = q.Where("firmwares_name like ?", in.FirmwaresName)

	}

	if in.Version != nil {

		q = q.Where("version like ?", in.Version)

	}

	if in.TacticsId != nil {

		q = q.Where("tactics_id = ?", in.TacticsId)

	}

	if in.SnCode != nil {

		q = q.Where("sn_code like ?", in.SnCode)

	}

	if in.Desc != nil {

		q = q.Where("desc like ?", in.Desc)

	}

	if in.Status != nil {

		q = q.Where("status = ?", in.Status)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&deviceUpgradeRecodes).Error; err != nil {
		return 0, nil, err
	}
	return int(total), deviceUpgradeRecodes, nil
}

// GetTacticsSuccessCount 获取策略下发成功数量
func (a *deviceUpgradeRecode) GetTacticsSuccessCount(ctx context.Context, tactics []int64) (successMap map[int64]int) {
	type Ret struct {
		TacticsId int64 `json:"tactics_id"`
		Count     int   `json:"count"`
	}

	successMap = make(map[int64]int)
	var rets []Ret
	if err := GetDB(ctx).Model(&entity.DeviceUpgradeRecode{}).Where("tactics_id in (?) and status = ?", tactics, 1).Select("tactics_id, count(*) as count").Group("tactics_id").Scan(&rets).Error; err != nil {
		return nil
	}

	for i := 0; i < len(rets); i++ {
		successMap[rets[i].TacticsId] = rets[i].Count
	}
	return
}

// ExecTransaction db事务执行
func (a *deviceUpgradeRecode) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, DBCONTEXTKEY, tx)
		return callback(ctx)
	})
}
